import React, { useState } from 'react'
import './search.css'
import { SearchBar } from '@nutui/nutui-react';
import {
    ArrowLeft,
    Photograph,
    Del,
} from '@nutui/icons-react'
import { useNavigate } from 'react-router-dom'
import axios from '../../axios';
import { useDispatch } from 'react-redux';
import { setSearchList } from '../../store/index'
export default function Search() {
    const [searchvalue, setValue] = useState('')
    const [list, setlist] = useState('')
    const navigate = useNavigate()
    const dispatch = useDispatch()
    let arr = [1, 2, 3, 4, 5, 6]
    arr.splice(arr.length - 1, 1, ...arr.splice(1, 1, arr[arr.length - 1]))

    let hisArr = JSON.parse(sessionStorage.getItem('hisArr')) || []
    let reverseHis = [...hisArr].reverse()

    let search = async (value) => {
        await axios.get('/search?key=' + value).then(val => {
            dispatch(setSearchList(val.data.data))
            setlist(val.data.data)
            navigate('/result')
            setValue('')
        })
    }

    function addHis(value) {
        let idx = hisArr.findIndex(item => item.title === value);
        if (idx === -1) {
            if (hisArr.length < 10) {
                hisArr.push({ id: new Date().getTime(), title: value });
            } else {
                const newHisArr = hisArr.slice(0, hisArr.length - 1);
                newHisArr.push({ id: new Date().getTime(), title: value });
                hisArr = newHisArr
            }
        }
        search(value)
        sessionStorage.setItem('hisArr', JSON.stringify(hisArr));
        navigate('/result')
    }

    function search1(keyword) {
        setValue(keyword)
        addHis(keyword)
    }

    function clearHis() {
        sessionStorage.removeItem('hisArr')
        window.location.reload()
    }

    function exchangeaddress(id) {
        let idx = hisArr.findIndex(item => item.id == id)
        let old = [...hisArr]
        old.splice(hisArr.length - 1, 1, ...old.splice(idx, 1, old[hisArr.length - 1]))
        sessionStorage.setItem('hisArr', JSON.stringify(old))
    }

    const handlesearch = (value) => {
        search(value)
        addHis(searchvalue)
    }
    const hotSearch = ['爱马仕', '指尖', '前端开发', '衬衫', 'iPhone', '外套']
    return (
        <div>
            <div className="top">
                <SearchBar
                    placeholder='请输入内容'
                    value={searchvalue}
                    clearable
                    onChange={(e) => setValue(e)}
                    shape="round"
                    left={
                        <>
                            <ArrowLeft width={20} height={20} onClick={() => navigate('/')} style={{
                            }} />
                        </>
                    }
                    right={
                        <>
                            <button onClick={() => { handlesearch(searchvalue) }}>搜索</button>
                        </>
                    }
                    rightIn={
                        <Photograph
                            width={16}
                            height={16}
                        />
                    }
                />
            </div>
            <div className="allsearch" style={{
                background: '#fff', height: '150px',
                width: '100%', padding: '5px 10px', boxSizing: 'border-box',
            }}>
                <div style={{ color: 'black', fontSize: '15px', fontWeight: 'bold', paddingLeft: '10px' }}>热门搜索</div>
                <div className='hot'>
                    {hotSearch.map(ele => {
                        return <button onClick={() => search1(ele)}>{ele}</button>
                    })}

                </div>
            </div >
            <div className='hisc'>
                <div className='his'>历史搜索</div>
                <div className='clearhis'><Del onClick={clearHis} /></div>
            </div>
            <div className="history" >
                {
                    reverseHis.map(item => (
                        <button clickable='true' key={item._id}
                            onClick={() => {
                                exchangeaddress(item.id)
                                addHis(item.title)
                            }}
                        >{item.title}</button>
                    ))
                }
            </div>
        </div>
    )
}
